package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.article.service.CollectionBehaviorService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {

    @Autowired
    private CacheService cacheService;

    /**
     * 收藏文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //todo 1.参数校验
        if(dto == null || dto.getEntryId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //todo 2.登录校验
        ApUser user = ApUserThreadLocalUtil.getUser();
        if(user == null || user.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //todo 3.判断是收藏还是取消收藏

        if(dto.getOperation() == 0){
            //todo 3.1 收藏，添加文章的收藏信息    用户ID     文章ID     dto
            Object o = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
            if(o != null){
                //代表已经收藏过了。
                return ResponseResult.errorResult(AppHttpCodeEnum.COLLECTION_EXIST);
            }
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else{
            //todo 3.2 取消收藏 删除文章的收藏信息
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
